#!/bin/bash

check_image(){
  echo "Check old instance's image..."
  echo "=== === === === ==="
  image_status=`ssh -Tq $hyper_id "/usr/bin/qemu-img check ${old_vm_file}"|grep 'No errors'|wc -l`
  if [[ $image_status != 1 ]];
  then
    echo "Error: ${old_vm_id}'s image has some error, cannot recover!"
    exit 1 
  fi
  echo "Start recover ${old_vm_id}..."
  echo "=== === === === ==="
}

update_and_lease_vm(){
  echo "Update db ${old_vm_id}'s status..."
  echo "=== === === === ==="
  ${exec_sql} -d zone -c "update instance set status='stopped' where instance_id='${old_vm_id}';" 2>/dev/null
  ${exec_sql} -d zone -c "select status from instance where instance_id='${old_vm_id}';" 2>/dev/null
  echo "Lease and start ${old_vm_id}..."
  echo "=== === === === ==="
  lease_status=`ssh -Tq $webservice_host "${python_env}${get_lease_cli} -r ${old_vm_id} -f ${cli_conf}"|grep -A 1 'lease_info'|grep 'status'|awk -F'\"' '{print $4}'`
  if [[ ${lease_status} != "active" ]];
  then
    ssh -Tq $webservice_host "${python_env}${lease_cli} -r ${old_vm_id} -u ${owner} -f ${cli_conf}"
  fi
  echo `ssh -Tq $webservice_host "${python_env}${get_lease_cli} -r ${old_vm_id} -f ${cli_conf}"|grep -A 1 'lease_info'`
  ssh -Tq $webservice_host "${python_env}${start_cli} -i ${old_vm_id} -f ${cli_conf}"
  echo "${old_vm_id} is recoverd..."
  echo "=== === === === ==="
}

old_vm_id=$1

if [[ $old_vm_id == "" ]];
then
  echo "Usage: ./recover-instances.sh <old_vm_id>"
  exit 1
fi

shell_pwd=`cd "$( dirname "$0" )" && pwd`
if [ ! -d "${shell_pwd}/cache" ];
then
  mkdir ${shell_pwd}/cache
fi
stat_file="${shell_pwd}/cache/old_${old_vm_id}.stat"
python_env="export PYTHONPATH=/pitrix/lib/pitrix-common:/pitrix/lib/pitrix-cli:\${PYTHONPATH};"
cli_conf="/pitrix/conf/client.yaml"
describe_cli="/pitrix/cli/describe-instances"
get_lease_cli="/pitrix/cli/get-lease-info"
lease_cli="/pitrix/cli/lease"
start_cli="/pitrix/cli/start-instances"
exec_sql="/pitrix/bin/exec_sql.py"
webservice_host=`grep webservice /etc/hosts|head -n 1|awk '{print $3}'`

echo "Getting old instance stats to old_vm.stat..."
echo "=== === === === ==="
ssh -Tq $webservice_host "${python_env}${describe_cli} -i ${old_vm_id} -f ${cli_conf}" >${stat_file}
hyper_id=`grep '"host_machine":"' ${stat_file}|tail -n 1|awk -F'\"' '{print $4}'`
hypervisor=`grep '"hypervisor":' ${stat_file}|tail -n 1|grep -v '""'|awk -F'\"' '{print $4}'`
owner=`grep '"owner":"' ${stat_file}|grep 'usr-'|tail -n 1|awk -F'\"' '{print $4}'`

if [[ $hyper_id == "" ]];
then
  echo "Error: ${old_vm_id} is not found!"
  exit 1
fi

if [[ $hypervisor == "kvm" ]];
then
  echo "Check old instance's data has been keeped..."
  echo "=== === === === ==="
  old_vm_file="/pitrix/data/container/__${old_vm_id}/archive/${old_vm_id}.img"
  ssh -Tq $hyper_id "ls ${old_vm_file}"
  if [[ $? != 0 ]];
  then
    old_vm_file="/pitrix/data/container/archive/${old_vm_id}.img"
    ssh -Tq $hyper_id "ls ${old_vm_file}"
    if [[ $? != 0 ]];
    then
      echo "Error: old instance archive is non-existent, cannot recover!"
      exit 1
    fi
    check_image
    old_size=$(ssh -Tq $hyper_id "du -b ${old_vm_file}"|awk '{print $1}')
    dir_size=$(ssh -Tq $hyper_id "df --block-size=1 /pitrix/data/container/|grep /"|awk '{print $4}')
    if [[ ${old_size} -lt ${dir_size} ]];
    then
      ssh -Tq $hyper_id "cp -f ${old_vm_file} /pitrix/data/container/"
      update_and_lease_vm
    else
      echo "Error: ${hyper_id}:/pitrix/data/container/ have not enough space."
      exit 1
    fi
  else
    check_image
    echo "Back-up archive to ${hyper_id}'s /pitrix/${old_vm_id}.img..."
    echo "=== === === === ==="
    old_size=$(ssh -Tq $hyper_id "du -b ${old_vm_file}"|awk '{print $1}')
    dir_size=$(ssh -Tq $hyper_id "df --block-size=1 /pitrix/|grep /"|awk '{print $4}')
    if [[ ${old_size} -ge ${dir_size} ]];
    then
      echo "Error: ${hyper_id}:/pitrix/ have not enough space."
      exit 1
    fi
    ssh -Tq $hyper_id "cp -f ${old_vm_file} /pitrix/${old_vm_id}.img"
    echo "Umount and rename vpool/__${old_vm_id}..."
    echo "=== === === === ==="
    ssh -Tq $hyper_id "fuser -m -k /pitrix/data/container/__${old_vm_id}"
    ssh -Tq $hyper_id "zfs umount vpool/__${old_vm_id}"
    if [[ $? != 0 ]];
    then
      echo "Error: zfs umount vpool/__${old_vm_id} failed!"
      exit 1
    fi
    ssh -Tq $hyper_id "zfs rename vpool/__${old_vm_id} vpool/${old_vm_id}"
    echo "Update mountpoint and mount vpool/${old_vm_id}..."
    echo "=== === === === ==="
    ssh -Tq $hyper_id "if [ ! -d /pitrix/data/container/${old_vm_id} ];then mkdir /pitrix/data/container/${old_vm_id};fi"
    ssh -Tq $hyper_id "zfs set mountpoint=/pitrix/data/container/${old_vm_id} vpool/${old_vm_id}"
    ssh -Tq $hyper_id "zfs mount vpool/${old_vm_id}"
    if [[ $? != 0 ]];
    then
      echo "Error: zfs mount vpool/${old_vm_id} failed!"
      exit 1
    fi
    ssh -Tq $hyper_id "mv /pitrix/data/container/${old_vm_id}/archive/${old_vm_id}.img /pitrix/data/container/${old_vm_id}/"
    update_and_lease_vm
  fi
else
  echo "The ${hypervisor} is not support for now!"
fi
